<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/4/24
 * Time: 8:54
 */

namespace app\admin\model;

use think\Model;

class ProxyMoney extends Model{

    protected $autoWriteTimestamp = true;

    /**
     * @param array $where
     * @param int $pageSize
     * @param string $field
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where= [], $pageSize=10,$field=''){
        $field = $field ? $field: "{$this->getTable()}.*,think_mch.name as mc_name";
        $list = $this
            ->field($field)
            ->join('think_mch',"think_member.id = {$this->getTable()}.mc_id")
            ->order($this->getTable().'.create_time desc')
            ->where($where)
            ->paginate($pageSize);
        return $list;
    }

    /**
     * 格式时间
     * @param $value
     * @return false|string
     */
    public function getUpdateTimeAttr($value){
        return  $value?date('Y-m-d H:i:s',$value):'--';
    }

    /**
     * @param string $name
     * @param string $aid
     * @param string $mc_id
     * @param int $money
     * @param int $type
     * @param int $proxy_id
     * @param string $out
     * @return $this|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addNew($name='',$aid='',$mc_id='',$money=0,$type=1,$proxy_id=0,&$out=''){
        $valid = new \app\admin\validate\ProxyMoney();
        if(!$proxy_id){
            $mch = new Mch();
            $_mch = $mch->where('id','eq',$mc_id)->find();
            $proxy_id = $_mch['proxy_id'];
        }
        $data = [
            'name'=>$name,
            'aid'=>$aid,
            'mc_id'=>$mc_id,
            'money'=>$money,
            'type'=>$type,
            'proxy_id'=>$proxy_id,
            'order_id'=>build_order_no()
        ];
        if(!$valid->check($data)){
            $out = $valid->getError();
            return false;
        }
        $proxy = new Proxy();
        $_proxy = $proxy->get($proxy_id);
        $_proxy->money = $_proxy['money']?$_proxy['money'] + $money: $money;
        if(!$_proxy->save()){
            $out = '操作失败';
            return false;
        }
        $this->data($data);
        return $this;
    }

    /**
     * 获取数据
     * @param int $id
     * @param string $field
     * @param int $limit
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getListByProxyId($id=0,$field='*',$limit=10){
        $list = $this
            ->field($field)
            ->where('proxy_id','eq',$id)
            ->paginate($limit);
        return $list;
    }
}